package SingleLinkedList;

public class MySingleLinkedList implements ISingleLinkedList {

    class ListNode {
        public int data;
        public ListNode next;

        public ListNode(int data) {
            this.data = data;
        }

    }

    public ListNode head;


    public void creatNode() {
        ListNode node1 = new ListNode(12);
        ListNode node2 = new ListNode(23);
        ListNode node3 = new ListNode(34);
        ListNode node4 = new ListNode(45);
        ListNode node5 = new ListNode(56);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        this.head = node1;
    }



    @Override
    public void display() {
        ListNode cur = head;
        while (cur != null){
            System.out.print(cur.data+" ");
            cur = cur.next;
        }
        System.out.println();
    }

    @Override
    public int size() {
        ListNode cur = head;
        int size = 0;
        while(cur != null){
            cur = cur.next;
            size++;
        }
        return size;
    }

    @Override
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        node.next = head;
        head = node;
    }

    @Override
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        ListNode cur = head;
        while(cur.next != null){
            cur = cur.next;
        }
        cur.next = node;
        node.next = null;
    }

    @Override
    public void addIndex(int index, int data) {
        ListNode node = new ListNode(data);
        ListNode cur = head;
        for(int i = 0; i < index-1; i++) {
            cur = cur.next;
        }
        node.next = cur.next;
        cur.next = node;
    }

    @Override
    public boolean contain(int key) {
        ListNode cur = head;
        while(cur != null){
            if(cur.data == key) return true;
            cur = cur.next;
        }
        return false;
    }

    @Override
    public void remove(int key) {
        if(head == null){
            return;
        }
        if(head.data == key) {
            head = head.next;
            return;
        }
        ListNode cur = head;
        while(cur.next != null){
            if(cur.next.data == key){
                cur.next = cur.next.next;
                return;
            }
            cur = cur.next;
        }
    }

    @Override
    public void removeAll(int key) {
        if(head == null) return;
        ListNode prev = head;
        ListNode cur = head.next;
        while(cur != null){
            if(cur.data == key){
                prev.next = cur.next;
            }else {
                prev = cur;
            }
            cur = cur.next;
        }
        if(head.data == key) head = head.next;
    }
}
